$(function () {
    const urls = {
        login: 'http://' + window.location.host + '/admin-public/login'
    };
    const inputs = {
        name: $("#input-name"),
        password: $("#input-password")
    };
    const btns = {
        login: $("#btn-login")
    };
    const forms = {
        login: $("#login-form")
    };
    const onLoginResponse = res => {
        if (typeof res === 'string') res = JSON.parse(res);
        if (res.code === 0) {
            window.location.href = '/index.html';
        } else {
            alert(res.msg);
        }
    };
    const onLogin = e => {
        e.preventDefault();
        const name = inputs.name.val();
        const password = inputs.password.val();
        if (name && password) {
            $.post(urls.login, {
                name,
                password
            }, onLoginResponse, 'json');
        } else {
            alert('请完善表单');
        }
        return false;
    };

    forms.login.submit(onLogin);
    btns.login.click(onLogin);
});